package org.arch_learn.servlet_container.components.connector;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import org.arch_learn.servlet_container.components.Service;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Endpoint extends SimpleChannelInboundHandler<HttpObject> {
    private Service service;

    private ChannelHandlerContext context;

    public Service getService() {
        return service;
    }

    public Endpoint(Service service) {
        this.service = service;
    }

    public void write(FullHttpResponse response) {
        context.writeAndFlush(response);
    }

    public void writeFile(FullHttpResponse response, RandomAccessFile randomAccessFile) throws IOException {
        DefaultFullHttpResponse defaultFullHttpResponse = (DefaultFullHttpResponse) response;
        context.write(defaultFullHttpResponse);
        ChunkedFile chunkedFile = new ChunkedFile(randomAccessFile, 0, randomAccessFile.length(), 8192);
        context.write(chunkedFile, context.newProgressivePromise());
        context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        context = channelHandlerContext;
        HttpRequest httpRequest = (HttpRequest)httpObject;
        String uri = httpRequest.uri();
        System.out.println("浏览器请求路径为：" + uri);

        new Connector(this).handleNettyHttpRequest(httpRequest);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getCause());
    }
}
